package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.ProductionLineSentBackAdapter;
import com.mflex.WHSmartWhouseAd.model.CombinedVehiclePdaResult;
import com.mflex.WHSmartWhouseAd.model.CommitProductionLineSendModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.ProductionLineSentBackPdaInfo;
import com.mflex.WHSmartWhouseAd.utils.MessageUtils;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//import butterknife.ButterKnife;


public class ProductionLineSentBackActivity extends BaseActivity implements AdapterView.OnItemClickListener  {
    // 操作人员
    EditText stvOperator;
    // 盘号
    EditText stvPackageNumber;
    // 楼层
    Spinner stvFloor;
    // FA/MP
    Spinner stvFaMp;
    // 已扫盘数
    EditText stvActualScanPlateNumber;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    // 提交
    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<ProductionLineSentBackPdaInfo>LineSentBarkModelList=new ArrayList<>();
    CommitProductionLineSendModel model = new CommitProductionLineSendModel();
    List<String> floorList = new ArrayList<>();
    private String userName;
    private String floorValue;
    private String fampValue;
    private double ActualScanPlateNumber=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_production_line_sent_back);
//        ButterKnife.bind(this);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
//        id绑定
        stvOperator = findViewById(R.id.stv_Operator);
        stvPackageNumber = findViewById(R.id.stv_PackageNumber);
        stvFloor = findViewById(R.id.stv_Floor);
        stvFaMp =findViewById(R.id.stv_FaMp);
        stvActualScanPlateNumber =findViewById(R.id.stv_ActualScanPlateNumber);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("User");
        // 视图按键监听器
        stvPackageNumber.setOnKeyListener(this);
        stvOperator.setOnKeyListener(this);
        buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvOperator.requestFocus();
        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
        // FA/MP下拉框列表
        List<String> faList = new ArrayList<>();
        faList.add("");
        faList.add("FA");
        faList.add("MP");

        ArrayAdapter<String> adapter1 =new ArrayAdapter<String>(this, com.king.zxing.R.layout.support_simple_spinner_dropdown_item,faList);
        adapter1.setDropDownViewResource(com.xuexiang.xpage.R.layout.support_simple_spinner_dropdown_item);
        stvFaMp.setAdapter(adapter1);
        stvFaMp.setSelection(0);
        stvFaMp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                fampValue = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 获取楼层下拉列表
        this.queryFloorList();
//        stvFloor.setSelection(0);
        // 获取下拉框当前选择的数据
        stvFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                floorValue = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                LineSentBarkModelList.clear();
                ProductionLineSentBackAdapter ProductionLineSentBackAdapter = new ProductionLineSentBackAdapter(ProductionLineSentBackActivity.this,LineSentBarkModelList);
                lvList.setAdapter(ProductionLineSentBackAdapter);
                stvPackageNumber.setText("");
                stvOperator.setText("");
                stvFloor.setSelection(0);
                stvFaMp.setSelection(0);
                ActualScanPlateNumber=0;
                stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_PackageNumber: // 盘号
                     chekPackageNumber();
                    break;
                case R.id.stv_Operator: // 操作人
                    chekOperator();
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    // 获取车间列表
    private void queryFloorList() {
        XHttp.get("api/WHSmartWhousePDA/GetFloor")
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<List<String>>() {
                    @Override
                    public  void  onSuccess(List<String> response) {
                        miniLoadingDialog.dismiss();
                        floorList = response;
                        ArrayAdapter<String> adapter =new ArrayAdapter<String>(ProductionLineSentBackActivity.this, com.king.zxing.R.layout.support_simple_spinner_dropdown_item,floorList);
                        adapter.setDropDownViewResource(com.xuexiang.xpage.R.layout.support_simple_spinner_dropdown_item);
                        stvFloor.setAdapter(adapter);
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(ProductionLineSentBackActivity.this, e.getMessage());
                    }
                });

    }
    // 扫操作人触发接口
    private void chekOperator() {
        if(StringUtils.isEmpty(stvOperator.getText().toString())) {
            return;
        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckActionUser")
                .params("UserName",stvOperator.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public  void  onSuccess(Boolean response) {
                        miniLoadingDialog.dismiss();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        stvOperator.setText("");
                        stvOperator.requestFocus();
                        MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }


//    箱号回车事件触发
    private void chekPackageNumber() {
        if(StringUtils.isEmpty(stvPackageNumber.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("盘号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        // 重复扫描卡控
        boolean ischeck = true;
        if(!LineSentBarkModelList.isEmpty()) {
            for(ProductionLineSentBackPdaInfo item: LineSentBarkModelList) {
                if(Objects.equals(item.getCode(), stvPackageNumber.getText().toString())) {
                    ischeck = false;
                    break;
                }
            }
        }
        if(!ischeck) {
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("盘号"+stvPackageNumber.getText().toString()+"在列表中已存在")
                    .positiveText(R.string.lab_submit)
                    .show();
            stvPackageNumber.setText("");
            stvPackageNumber.requestFocus();
            return;
        }
      // start 测试
//        ProductionLineSentBackPdaInfo items = new ProductionLineSentBackPdaInfo();
//        items.setReelID("qwert");
//        items.setJDEMaterial("20241202");
//        items.setQty("100");
//        LineSentBarkModelList.add(items);
//        ActualScanPlateNumber = LineSentBarkModelList.size();
//        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
//        ProductionLineSentBackAdapter ProductionLineSentBackAdapter = new ProductionLineSentBackAdapter(ProductionLineSentBackActivity.this,LineSentBarkModelList);
//        lvList.setAdapter(ProductionLineSentBackAdapter);
      // end
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/GetReelByCode")
                .params("code",stvPackageNumber.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<ProductionLineSentBackPdaInfo>() {
                    @Override
                    public  void  onSuccess(ProductionLineSentBackPdaInfo response) {
                        miniLoadingDialog.dismiss();
                        LineSentBarkModelList.add(response);
                        ActualScanPlateNumber = LineSentBarkModelList.size();
                        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
                        ProductionLineSentBackAdapter ProductionLineSentBackAdapter = new ProductionLineSentBackAdapter(ProductionLineSentBackActivity.this,LineSentBarkModelList);
                        lvList.setAdapter(ProductionLineSentBackAdapter);
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                        MediaPlayer mp =MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }
//    提交
    private void saveButtonMd(View v) {
        if(LineSentBarkModelList.isEmpty()){
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("盘号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(stvOperator.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("操作人未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(floorValue)) {
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("楼层未选择")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(fampValue)) {
            MediaPlayer mp = MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("FA/MP未选择")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        model.setTxnUser(stvOperator.getText().toString());
        model.setFloor(floorValue);
        model.setTxnType(fampValue);
        model.setProductionRebackDtos(LineSentBarkModelList);

//        CommonRequest request =new CommonRequest();
//        request.setJson(JsonUtil.toJson(model));
        String json = JsonUtil.toJson(model);
        Log.d("1234",json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/SendLotReturn")
                .upJson(JsonUtil.toJson(model))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(150000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        LineSentBarkModelList.clear();
                        ProductionLineSentBackAdapter ProductionLineSentBackAdapter = new ProductionLineSentBackAdapter(ProductionLineSentBackActivity.this,LineSentBarkModelList);
                        lvList.setAdapter(ProductionLineSentBackAdapter);
                        stvPackageNumber.setText("");
                        stvOperator.setText("");
                        ActualScanPlateNumber=0;
                        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(ProductionLineSentBackActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(ProductionLineSentBackActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}